import axios from 'axios'
import store from '../store'
import router from '../router'
import Base from './base64.js'//导入加密
import Coke from './coke.js'//导入Coke
//设置api的前缀
axios.defaults.baseURL = "http://192.168.1.188:12";

// post请求的时候，我们需要加上一个请求头，所以可以在这里进行一个默认的设置
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

//请求拦截器
axios.interceptors.request.use((config) => {
  config.headers.common['Authorization'] = store.state.token//请求头加token
  return config;
}, (error) => {
  return Promise.reject(error);
});

//响应拦截器
axios.interceptors.response.use((response) => {
  return response;
}, (error) => {
  // 对响应错误做点什么
  let url = error.config.url;
  if (error.response.status == 401 && !url.endsWith("/api/OAuth/authenticate")) {
    let account = Coke.getCookie("account")//获取加密账号
    let pass = Coke.getCookie("pass")//获取加密密码
    if (account && pass) {
      //重新调用登录接口来获取新的token
      return GetToken({ account, pass }, error)
    } else {
      toLogin()//跳转到登录页
    }
  }
  return Promise.reject(error);
});

//重新获取Token
async function GetToken(user, error) {
  let response = await axios.get("/api/OAuth/authenticate", {
    params: {
      userMobile: Base.base64decode(user.account),
      userPassword: Base.base64decode(user.pass)
    }
  }).catch(() => {
    toLogin()//跳转到登录页
  })
  if (response.status == 200 && response.data) {
    store.dispatch('gettoken',response.data.token_type + " " + response.data.access_token)//在状态管理里面存入token
    store.dispatch('getuserUid',response.data.profile.userUid)//在状态管理存入userUid
    store.dispatch('getcircleUrl',response.data.profile.userHeader)//在状态管理存入用户头像
    store.dispatch('getuserUserTypeId',response.data.profile.userUserTypeId)//在状态管理中存入userUserTypeId权限
    error.config.headers.Authorization = response.data.token_type + " " + response.data.access_token//请求头加token
    return await axios(error.config)
  }
}
/**
 * 跳转登录页
 * 携带当前页面路由，以期在登录页面完成登录后返回当前页面
 */
const toLogin = () => {
  router.replace({
    path: '/login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  });
}

/*
*post 请求方法
* @param url
* @param data
* @returns {Promise}
 */
export  function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response)
      }).catch(err => {
      reject(err)
    })
  })
}
/*
*get 请求方法
* @param url
* @param data
* @returns {Promise}
 */
export  function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params
    })
      .then(response => {
        resolve(response)
      }).catch(err => {
      reject(err)
    })
  })
}
